package com.salon.client.widgets;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.form.SimpleComboValue;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.salon.client.GreetingServiceAsync;
import com.salon.client.Salon;
import com.salon.client.beans.MasterBean;
import com.salon.client.beans.MaterialBean;
import com.salon.client.tabItems.MasterTabItemPanel;
import com.salon.client.tabItems.MaterialTabItemPanel;

public class MaterialDialog extends Dialog {
	protected TextField<String> name = new TextField<String>();
	protected TextField<String> code = new TextField<String>();
	protected TextField<String> desc = new TextField<String>();
	protected TextField<String> made = new TextField<String>();
	protected NumberField cost = new NumberField();
	protected SimpleComboBox<String> isCounted = new SimpleComboBox<String>();
	protected NumberField wieght = new NumberField();
	protected MaterialBean bean = null;
	private MaterialTabItemPanel parentPanel;
	private final String gramm = "грамм";
	private final String shtuk = "штук";
	
	public MaterialDialog(MaterialTabItemPanel panel, MaterialBean bean) {
		parentPanel = panel;
		this.bean = bean;
		setHeading((bean == null) ? "Добавление материала" : "Редактирование материала");
		FormLayout layout = new FormLayout();
	    layout.setLabelWidth(130);
	    layout.setDefaultWidth(300);
	    setLayout(layout);
	    
	    setButtonAlign(HorizontalAlignment.CENTER);
	    setButtons(Dialog.OKCANCEL);
	    
	    setIcon(IconHelper.createStyle("user"));
	    setModal(true);
	    setBodyBorder(true);
	    setBodyStyle("padding: 8px;background: none");	
	    setWidth(500);
	    setResizable(false);
	    
	    code.setFieldLabel("Код");
	    add(code);
	    
	    name.setFieldLabel("Наименование");
	    add(name);
	    
	    desc.setFieldLabel("Описание");
	    add(desc);
	    
	    made.setFieldLabel("Производитель");
	    add(made);
	    
	    NumberFormat nf = NumberFormat.getFormat("##.##");
	    cost.setFormat(nf);
	    cost.setFieldLabel("Цена");
	    add(cost);
	    
	    isCounted.setFieldLabel("Измеряется в");
	    isCounted.add(shtuk);
	    isCounted.add(gramm);
	    isCounted.setEditable(false);
	    isCounted.setTriggerAction(TriggerAction.ALL);
	    /*isCounted.addSelectionChangedListener(new SelectionChangedListener<SimpleComboValue<String>>() {

			@Override
			public void selectionChanged(
					SelectionChangedEvent<SimpleComboValue<String>> se) {
				if (se.getSelectedItem().getValue().equals(shtuk)) {
					wieght.setValue(null);
					wieght.setEnabled(false);
				}
				else {
					wieght.setEnabled(true);
				}
				
			}
	    	
	    });*/
	    add(isCounted);
	    
	    wieght.setFieldLabel("Вес");
	    add(wieght);
	    
	    if (bean != null) {
	    	fillData();
	    }
	    Button ok = getButtonById(Dialog.OK);
		ok.setText("ОК");
		ok.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				if (MaterialDialog.this.bean == null) {
					if (!getData(true)) {
						return;
					}
					((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
					addMaterial(MaterialDialog.this.bean, new AsyncCallback<Void>() {
	
						@Override
						public void onFailure(Throwable caught) {
							Info.display("Не удалось", "Добавить материал");
							
						}
	
						@Override
						public void onSuccess(Void result) {
							Info.display("Добавление материала", "Успешно");
							MaterialDialog.this.hide();
							if (MaterialDialog.this.parentPanel != null) {
								MaterialDialog.this.parentPanel.refreshStore();
							}
						}
						
					});
				}
				else {
					if (!getData(false)) {
						return;
					}
					((GreetingServiceAsync) Registry.get(Salon.SERVICE)).
					updateMaterial(MaterialDialog.this.bean, new AsyncCallback<Void>() {
	
						@Override
						public void onFailure(Throwable caught) {
							Info.display("Не удалось", "Редактировать материал");
						}
	
						@Override
						public void onSuccess(Void result) {
							Info.display("Редактирование материала", "Успешно");
							MaterialDialog.this.hide();
							if (MaterialDialog.this.parentPanel != null) {
								MaterialDialog.this.parentPanel.refreshStore();
							}
						}
						
					});
				}
			}
			
		});
		
	    Button cancel = getButtonById(Dialog.CANCEL);
	    cancel.setText("Отмена");
	    cancel.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				MaterialDialog.this.hide();
				
			}
	    });
	}
	
	private void fillData() {
		name.setValue(bean.getName());
		isCounted.setSimpleValue(bean.getIsContedAsString());
		code.setValue(bean.getCode());
		desc.setValue(bean.getDecs());
		made.setValue(bean.getMade());
		cost.setValue(bean.getCost());
		wieght.setValue(bean.getWeight());
	}
	
	private boolean getData(boolean isAdd) {
		if (name.getValue() == null || name.getValue().isEmpty()) {
			Info.display("Введите", "Наименование товара");
			name.focus();
			return false;
		}
		
		if (isCounted.getSimpleValue() == null || isCounted.getSimpleValue().isEmpty()) {

			Info.display("Выберите", "Единицу измерения");
			isCounted.focus();
			return false;
		}
		
		if (isAdd) {
			bean = new MaterialBean();
		}
		
		bean.setName(name.getValue());
		bean.setIsConted(isCounted.getSimpleValue().equals(shtuk));

		//if (code.getValue() != null) && !code.getValue().isEmpty()) {
			bean.setCode(code.getValue());
		//}
		//if (desc.getValue() != null && !desc.getValue().isEmpty()) {
			bean.setDecs(desc.getValue());
		//}
		//if (made.getValue() != null && !made.getValue().isEmpty()) {
			bean.setMade(made.getValue());
		//}
		if (cost.getValue() != null) {
			bean.setCost(cost.getValue().floatValue());
		}
		else {
			bean.setCost(0);
		}
		
		//if (!bean.getIsConted()) {
			if (wieght.getValue() != null) {
				bean.setWeight(wieght.getValue().intValue());
			}
			else {
				bean.setWeight(0);
			}
		//}
		return true;
	}
}